import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Player } from './player';

@Injectable()
export class PlayerService {
    private playersUrl = 'http://121.40.82.99:8003/apis/soccer/players';  // URL to web API
    private updatePlayerUrl = 'http://localhost:8003/apis/soccer/players/update';

    constructor(private http: Http) { }

    getPlayers(): Promise<Player[]> {
        // .toPromise(this.extractData, this.handleError)
        return this.http.get(this.playersUrl)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }
    updatePlayer(player: Player): Promise<Response> {
        return this.http.post(this.updatePlayerUrl, player).toPromise().catch(this.handleError);
    }
    private extractData(res: Response) {
        let body = res.json();
        return body.players.slice(-5, -1) || {};
    }
    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Promise.reject(errMsg);
    }
}